package lvbu.wang.lvbuoperator.ui.error;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

import lvbu.wang.lvbuoperator.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           R;
import lvbu.wang.lvbuoperator.bean.SendCommandResult;
import lvbu.wang.lvbuoperator.core.BaseActivity;
import lvbu.wang.lvbuoperator.manager.ThreadPool;
import lvbu.wang.lvbuoperator.services.BluetoothLEService;
import lvbu.wang.lvbuoperator.utils.CommandUtils;
import lvbu.wang.lvbuoperator.utils.StringHelper;

/**
 * Created by DaiQing.Zha on 2017/1/2 0002.
 */
public class BleErrorActivity extends BaseActivity {

    private TextView mTvErrorInfo;  //显示错误信息的TextView控件
    private Button mBtnRefresh;    //刷新按钮
    private int[] mErrorCodeArr = {0x01,0x02,0x04,0x08,0x10,0x20,0x40}; //错误代码数组，各个错误代码所表示的意义见getErrorInfo()方法
    private List<String> mExistError = new ArrayList();                //已经存在的错误集合，若某个错误在该集合中已经存在，那么将不把该错误添加进来，避免重复显示

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ble_see_error);
    }
    @Override
    protected void init() {
        mBtnRefresh = (Button) findViewById(R.id.btn_refresh);
        mTvErrorInfo = (TextView) findViewById(R.id.tv_errorInfo);
        mBtnRefresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getErrorInfo();
            }
        });
        getErrorInfo();
        getSupportActionBar().setTitle("错误详情");
    }
    /**
     * 获取电机错误信息
     */
    private void getErrorInfo(){
        ThreadPool.getInstance().addTask(new Runnable() {
            @Override
            public void run() {

                String commandHead = "C9";
                String sendCode = CommandUtils.FLAG_GET + commandHead;
                SendCommandResult scr = BluetoothLEService.sendCommandByBluetooth(sendCode,CommandUtils.getInquireCommand(new String[]{commandHead}));

                if (scr.isResult()) {
                    answerProcessNewProtocol(scr.getAnswerContent());
                } else {
                    answerErrorNewProtocol(sendCode, scr.getErrorMessage());
                }
            }
        });
    }

    /**
     * 新蓝牙协议应答正确处理
     * @param answerContent
     */
    private void answerProcessNewProtocol(String answerContent){
        String flag = StringHelper.subString(answerContent,4,6);
        String answerResult = StringHelper.subString(answerContent,6,8);
        if (CommandUtils.FLAG_SET.equals(flag)){
            String key = flag + StringHelper.subString(answerContent,8,10);
            String value = StringHelper.subString(answerContent,10,answerContent.length() - 4);
            answerProcessNewProtocol(key,value,answerResult);
        }else if (CommandUtils.FLAG_GET.equals(flag)){
            HashMap map = CommandUtils.getInquireMap(answerContent);
            Set set1 = map.keySet();
            for (Object obj : set1) {
                String key = CommandUtils.FLAG_GET + String.valueOf(obj.toString());
                String value = String.valueOf(map.get(obj));
                answerProcessNewProtocol(key,value,answerResult);
            }
        }
    }
    /**
     * 新蓝牙协议应答正确处理（单个命令）
     * @param key
     * @param value
     */
    private void answerProcessNewProtocol(String key,String value,String answerResult){
        switch (key){
            case "0CC9":
                if ("01".equals(answerResult)) { //应答成功
                    String errorCodeS = value;
                    int errorCode = Integer.parseInt(errorCodeS,16);    //电机返回的错误代码
                    String errorInfo = "";
                    int j = 0;
                    /**
                     * 将该错误代码跟错误代码数组中的每一项进行与操作，得到一个错误代码
                     * 然后根据得到的错误代码获取错误信息
                     * 接着判断该错误信息是否重复
                     * 若没有重复则将该错误信息添加进已经存在的错误集合中
                     */
                    for (int i = 0; i < mErrorCodeArr.length; i ++){
                        int errorCodeA = errorCode & mErrorCodeArr[i];
                        if (!"".equals(getErrorInfo(errorCodeA))){
                            if (!isExist(getErrorInfo(errorCodeA))){
                                mExistError.add(getErrorInfo(errorCodeA));
                                j ++;
                                errorInfo = errorInfo + j + "、" + getErrorInfo(errorCodeA) + "\n";
                            }
                        }
                    }
                    mExistError.clear();
                    final String finalErrorInfo = errorInfo;
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mTvErrorInfo.setText(finalErrorInfo);
                        }
                    });
                }else{
                    mTvErrorInfo.setText("查询错误失败!!!");
                }
                break;
        }
    }

    /**
     * 新蓝牙协议应答错误处理
     * @param key
     * @param errorMessage
     */
    private void answerErrorNewProtocol(String key,String errorMessage){
        switch (key){
            case "0CC9":
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mTvErrorInfo.setText("查询错误失败!!!");
                    }
                });
                break;
        }
    }

    /**
     * 应答正确处理
     * @param answerContent
     */
    private void answerProcess(String answerContent) {
        String sendCode = answerContent.substring(2,4).toUpperCase();
        String answerResult = answerContent.substring(4,6);
        switch (sendCode){
            case "B3":  //初始化电机信息
                if ("01".equals(answerResult)){ //应答成功
                    String errorCodeS = answerContent.substring(6,8);
                    int errorCode = Integer.parseInt(errorCodeS,16);    //电机返回的错误代码
                    String errorInfo = "";
                    int j = 0;
                    /**
                     * 将该错误代码跟错误代码数组中的每一项进行与操作，得到一个错误代码
                     * 然后根据得到的错误代码获取错误信息
                     * 接着判断该错误信息是否重复
                     * 若没有重复则将该错误信息添加进已经存在的错误集合中
                     */
                    for (int i = 0; i < mErrorCodeArr.length; i ++){
                        int errorCodeA = errorCode & mErrorCodeArr[i];
                        if (!"".equals(getErrorInfo(errorCodeA))){
                            if (!isExist(getErrorInfo(errorCodeA))){
                                mExistError.add(getErrorInfo(errorCodeA));
                                j ++;
                                errorInfo = errorInfo + j + "、" + getErrorInfo(errorCodeA) + "\n";
                            }
                        }
                    }
                    mExistError.clear();
                    final String finalErrorInfo = errorInfo;
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mTvErrorInfo.setText(finalErrorInfo);
                        }
                    });
                }else{  //应答失败
                    mTvErrorInfo.setText("查询错误失败!!!");
                }
                break;
        }
    }
    /**
     * 应答错误处理
     * @param sendCode
     * @param errorMessage
     */
    private void answerError(String sendCode, String errorMessage) {
        switch (sendCode){
            case "B3":
                mTvErrorInfo.setText("查询错误失败!!!");
                break;
        }
    }

    /**
     * 判断错误是否存在
     * @param value
     * @return
     */
    private boolean isExist(String value){
        if (mExistError.contains(value)){
            return true;
        }else{
            return false;
        }
    }
    /**
     * 获取错误信息
     * @param code
     * @return
     */
    private String getErrorInfo(int code){
        String error = "";
        if (code == 0x01){
            error = "电机过流或MOS管突然击穿";
        }
        if (code == 0x02){
            error = "电机堵转";
        }
        if (code == 0x04){
            error = "电机桥臂故障或驱动电路异常";
        }
        if (code == 0x08){
            error = "电机霍尔异常_08";
        }
        if (code == 0x10){
            error = "陀螺仪异常";
        }
        if (code == 0x20){
            error = "24C02异常";
        }
        if (code == 0x40){
            error = "电机霍尔异常_40";
        }
        return error;
    }
}
